package com.horay.nettydemo.nio.file;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.unit.DataSize;
import org.springframework.util.unit.DataUnit;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.function.Consumer;

/**
 * 拷贝文件
 *
 * @author heyingcheng
 * @date 2019/11/23 21:10
 */
@Slf4j
public class CopyFileByRead {

    private static final String FROM_PATH_NAME = "D:/root/cctv-support-logs/support-gsnw-8080/logs/catalina/catalina.2019-09-20.log";
    private static final String TO_PATH_NAME = "D:/root/cctv-support-logs/support-gsnw-8080/logs/catalina/catalina.2019-09-20-copy-01.log";

    public static void main(String[] args) {
        File fromFile = new File(FROM_PATH_NAME);
        File toFile = new File(TO_PATH_NAME);
        copyFile(fromFile, toFile);
    }

    private static void copyFile(File fromFile, File toFile) {
        try (FileInputStream fileInputStream = new FileInputStream(fromFile);
             FileOutputStream fileOutputStream= new FileOutputStream(toFile);
             FileChannel fromChannel = fileInputStream.getChannel();
             FileChannel toChannel = fileOutputStream.getChannel()) {
            ByteBuffer byteBuffer = ByteBuffer.allocate(Math.toIntExact(DataSize.ofKilobytes(1L).toBytes()));

            int read = 0;
            for (;;) {
                byteBuffer.clear();
                read = fromChannel.read(byteBuffer);
                if (read == -1) {
                    break;
                }
                byteBuffer.flip();
                toChannel.write(byteBuffer);
            }
        } catch (FileNotFoundException e) {
            log.error("拷贝文件异常", e);
        } catch (IOException e) {
            log.error("拷贝文件异常", e);
        }
    }

}
